/**
 * EditMetadataServlet.java
 * Retrieves and allows editing of existing media file metadata
 * through related data access and data transfer objects.
 */
package com.example.myproject;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class EditMetadataServlet extends HttpServlet {
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String fileType = req.getParameter("fileType")==null?"audio":req.getParameter("fileType");
		Long id = Long.parseLong(req.getParameter("id")==null?"0":req.getParameter("id"));
		String title = req.getParameter("title");
		String series = req.getParameter("series");
		String episode = req.getParameter("episode");
		String album = req.getParameter("album");
		String genre = req.getParameter("genre");
		String caption = req.getParameter("caption");
		
		// Determine the selected file's content and edit
		// related metadata fields.
		if("audio".equals(fileType))
		{
			
			AudioUploadDAO audio = new AudioUploadDAO();
			AudioUploadDTO dto = new AudioUploadDTO();
			
			/* 
			 * it retrieve formal data 
			 * make audio datastore keep connecting with blobkey
			 */
			dto = audio.findById(id);
			
			dto.setTitle(title);
			dto.setAlbum(album);
			dto.setGenre(genre);
			dto.setCaption(caption);
			dto.setId(id);

			/*
			 * There is no update function in Objectify
			 * so simply delete and save again
			 */
			audio.delete(id);
			audio.save(dto);
			
		}
		else if("video".equals(fileType))
		{
			
			VideoUploadDAO video = new VideoUploadDAO();
			VideoUploadDTO dto = new VideoUploadDTO();
			
			dto = video.findById(id);
			
			dto.setTitle(title);
			dto.setSeries(series);
			dto.setEpisode(episode);
			dto.setCaption(caption);
			dto.setId(id);			
			
			video.delete(id);
			video.save(dto);
		
		}
		else if("image".equals(fileType))
		{
			
			PictureUploadDAO picture = new PictureUploadDAO();
			PictureUploadDTO dto = new PictureUploadDTO();
			
			dto = picture.findById(id);
			
			dto.setTitle(title);
			dto.setId(id);
			dto.setCaption(caption);
			
			picture.delete(id);
			picture.save(dto);
			
		}
		else if("book".equals(fileType))
		{
			
			BookUploadDAO book = new BookUploadDAO();
			BookUploadDTO dto = new BookUploadDTO();
			
			dto = book.findById(id);
			dto.setTitle(title);
			dto.setId(id);		
			dto.setCaption(caption);
			
			book.delete(id);
			book.save(dto);
			
		}		
	 		
		resp.sendRedirect("index.jsp");	
			
	}

}